# -*- coding:utf8 -*-
#encoding = utf-8
__author__ = 'man' 

#		_________________________________________________________________________________
#
#						漫鸽网络技术服务(mangenotwork)拥有所有权
#						@www.hbsj.xyz   
#						@www.mangenotwork.com
#			严重声明：原始代码属于"漫鸽网络技术服务(mangenotwork)"的知识产权，拥有法律的保护，
#		请勿抄袭、转载、删除、私用、篡改、破坏...
#
#       
#		简介 ：  collect.py 收藏API
#		作者 ： 李漫(man)
#		创建时间:  20190620
#		
#		_________________________________________________________________________________

from flask import Flask,request,g,render_template,redirect,url_for,abort,session,jsonify,current_app
from flask import Blueprint , render_template
from flask import make_response,Response 
import sys,os
import json
import time
import datetime
import redis
from cryptography.fernet import Fernet
#md5
import hashlib
import db.mandb
import random
import re

'''
man_db = db.mandb.DB()
print(man_db.db_connect())
'''
wenzhang = Blueprint('wenzhang',__name__)
#函数不能命名 test



'''
					#类型： DB交互
					#执行查询  查询结果
'''
def ManDB(func=None, param=None):
	def deco(func):
		def wrapper(*args,**kwargs):
			man_db = db.mandb.DB()
			return func(man_db,*args,**kwargs)			
		wrapper.__name__ = func.__name__
		return wrapper
	return deco if not func else deco(func)


@wenzhang.route('/wenzhang_test', methods=['POST','GET'])
def wenzhang_test():
	return "This is a Blueprint : wenzhang Test."


# 文章列表显示的数据格式
def wz_list_show(wz):
	returnlist = []
	for data in wz:
		if data[2] == '0':
			info = {
				"show1":"1",
				"id":data[0],
				"title":data[1],
				"fenlei":data[3],
				"date":data[4],
				"pl":data[5],
				"ck":data[6],
				"type":data[7]
			}
			returnlist.append(info)
			info = {}
		else:
			images_list = data[2].split("|")
			images_len = len(images_list)
			if images_len >= 3:
				images_list = images_list[0:3]
				images_len = 3
			info = {
				"showimg":"1",
				"id":data[0],
				"title":data[1],
				"imgs":images_list,
				"img_len":images_len,
				"fenlei":data[3],
				"date":data[4],
				"pl":data[5],
				"ck":data[6],
				"type":data[7]
			}
			returnlist.append(info)
			info = {}
	return returnlist


#首页文章
@wenzhang.route('/', methods=['POST','GET'])
def index_pg():
	wz = get_home_wz()
	returnlist = wz_list_show(wz)
	#print(returnlist)
	return render_template('home.html', wzlist=returnlist, tj=1, htmltitle = "始终养生头条")


#获取当天的文章,让用户误认为每天都有新的文章更新
@ManDB
def get_home_wz(man_db):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
			FROM `szys_list` \
			WHERE ysdate = DATE_FORMAT(NOW(),'%Y-%m-%d') \
			order by rand() \
			LIMIT 0,50"
	return_datas = man_db.execute_seles(sql)
	return return_datas

'''
SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype
FROM `szys_list` 
WHERE str_to_date(ysdate, '%Y-%m-%d') BETWEEN str_to_date('2018-05-23', '%Y-%m-%d') AND CURDATE() ORDER BY str_to_date(ysdate, '%Y-%m-%d') DESC
LIMIT 0,30


SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype
FROM `szys_list` 
WHERE ysdate = DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 DAY), '%Y-%m-%d')
LIMIT 0,30



SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype
FROM `szys_list` 
WHERE ysdate = DATE_FORMAT(NOW(),'%Y-%m-%d')
LIMIT 0,30

SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype
FROM `szys_list` 
WHERE ysdate = '2019-07-22'
LIMIT 0,30


'''


#阅读数加一
@ManDB
def addyd_number(man_db,ids):
	#该文章的阅读数加1
	addyd_sql = "UPDATE szys_list \
		set ck_count = ck_count+1 \
		where szys_id = '"+str(ids)+"' ;"
	man_db.execute(addyd_sql)



#获取 zd 的文章
@ManDB
def get_zd_wz(man_db,ids):
	sql = "SELECT sydata_dzys.title, sydata_dzys.content, szys_list.imgpath, szys_list.fenlei, szys_list.ysdate,\
			szys_list.pl_count,szys_list.ck_count,szys_list.zhan,szys_list.szys_id \
			FROM sydata_dzys,szys_list \
			WHERE sydata_dzys.sydata_id=substring(szys_list.szys_id,4) and szys_list.szys_id = '"+str(ids)+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas[0]



#获取 tt 的文章
@ManDB
def get_tt_wz(man_db,ids):
	sql = "SELECT sydata_ttys.title, sydata_ttys.content, szys_list.imgpath, szys_list.fenlei, szys_list.ysdate,\
			szys_list.pl_count,szys_list.ck_count,szys_list.zhan,szys_list.szys_id \
			FROM sydata_ttys,szys_list \
			WHERE sydata_ttys.sydata_id=substring(szys_list.szys_id,4) and szys_list.szys_id = '"+str(ids)+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas[0]



# 文章内容显示的数据格式
def wz_nr_show(wz_info,wz_info_data):
	
	if wz_info[5] == 0:
		returninfo = {
				"title":wz_info[0],
				"info":wz_info_data,
				"fenlei":wz_info[3],
				"time":wz_info[4],
				"notpl":1,
				"ck":wz_info[6],
				"zhan":wz_info[7],
				"id":wz_info[8]		
		}
	else:
		returninfo = {
				"title":wz_info[0],
				"info":wz_info_data,
				"fenlei":wz_info[3],
				"time":wz_info[4],
				"getpl":1,
				"ck":wz_info[6],
				"zhan":wz_info[7],
				"id":wz_info[8]
		}
	return returninfo


#查看文章
@wenzhang.route('/read', methods=['POST','GET'])
def readinfo():
	if request.method == "GET":
		wz_type = request.args.get('type')
		wz_id = request.args.get('id')
	#wz_info = get_zd_wz()
	print(wz_type)
	print(wz_id)
	addyd_number(wz_id)
	#如果文章类型是 dz 就请求dz表里的数据
	if wz_type =="dz":
		#ids = wz_id.split("_")[-1]
		wz_info = get_zd_wz(wz_id)
		#清理指定的内容  dz 类型的文章是以 \r\n\r\n 换行
		wz_info_data = wz_info[1].replace(" ","&nbsp")
		wz_info_data = wz_info_data.replace("\r\n\r\n\r\n","\r\n\r\n")
		wz_info_data = wz_info_data.replace("\r\n","<br>&nbsp&nbsp")
		returninfo = wz_nr_show(wz_info,wz_info_data)
		
	#如果文章类型是 tt 就请求tt表里的数据
	elif wz_type =="tt":
		#ids = wz_id.split("_")[-1]
		wz_info = get_tt_wz(wz_id)
		#清理指定的内容
		wz_info_data = wz_info[1].replace(" ","&nbsp")
		wz_info_data = wz_info[1].replace("天天养生","【始终养生头条】")
		#清理垃圾字符
		ccc = ["\\u201c","\\u201d","\\u2026"]
		for cc in ccc:
			#print(cc)
			wz_info_data = wz_info_data.replace(cc,"")
		# tt 类型的文章是以 \u3000\u3000 分段
		wz_coun = wz_info_data.split("\u3000\u3000")
		#print("[wz_coun] = ")
		#print(wz_coun)
		#插入图片的游标
		imgnumber = 0
		#print("wz_info[2]")
		#print(wz_info[2])
		#该文章的所有图片
		imglists = wz_info[2].split("|")
		#该文章的图片个数
		imglens = len(imglists)
		#print("[imglists] = ")
		#print(imglists)
		#print("[imglens] = ")
		#print(imglens)
		#插入图片，根据游标，游标数要小于该文章的图片的总数
		while imgnumber<imglens:
			#插入图片的格式 没两个换行就插入
			imginfo = '<img class="img-rounded wz_imgs" src="http://hbsj.qiye6666.com'+imglists[imgnumber]+'">'
			wz_coun.insert((imgnumber+1)*2,imginfo)
			imgnumber+=1
		#分段换行
		wz_couns = "<br><br>&nbsp&nbsp".join(wz_coun)
		#wz_info_data = wz_couns.replace("\u3000\u3000","<br><br>")
		#如果评论数是0 返回显示不同的评论列表视图
		returninfo = wz_nr_show(wz_info,wz_couns)	
	print(returninfo)
	return render_template('ysinfo.html',wzinfo = returninfo ,wz_type = wz_type, wz_id=wz_id, htmltitle = wz_info[0])



#获取语音包
@wenzhang.route('/getsound', methods=['POST','GET'])
def get_sound():
	if request.method == "GET":
		wz_type = request.args.get('type')
		wz_id = request.args.get('id')
		pack = request.args.get('pack')

	if pack == None:
		pack = 0
	else:
		pack = int(pack)

	if wz_type =="dz":
		wz_info = get_zd_wz(wz_id)
		sound_data = wz_info[1].replace("\r\n","")
		sound_data = sound_data.replace(" ","")
		ccc = ["、","。","，","‘","？","："]
		for cc in ccc:
			#print(cc)
			sound_data = sound_data.replace(cc,"")
	elif wz_type =="tt":
		wz_info = get_tt_wz(wz_id)
		sound_data = wz_info[1].replace("\r\n","")
		sound_data = sound_data.replace(" ","")
		ccc = ["、","。","，","‘","？","："]
		for cc in ccc:
			#print(cc)
			sound_data = sound_data.replace(cc,"")
	#print(sound_data)
	#print(len(sound_data)/500)

	sound_data = wz_info[0] + sound_data
	pat=re.compile(r'[\u4e00-\u9fa5]+')
	sound_data_result=pat.findall(sound_data)
	sound_data_info = "".join(sound_data_result)

	print(sound_data_info)

	film_type_new = []
	for i in range(0, len(sound_data_info), 500):
		film_type_new.append(sound_data_info[i:i+500])
	print(film_type_new)
	print(len(film_type_new))

	if pack >= len(film_type_new):
		pack = -1

	returnjson_data = {
		"pack_count": len(film_type_new),
		"pack":pack,
		"sound_data":film_type_new[pack]
	}
	return json.dumps(returnjson_data).encode('utf-8').decode("unicode-escape")




#搜索功能 
@ManDB
def search_wz(man_db,keys,numberpg=0):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
		from szys_list where title like '%"+str(keys)+"%' \
		and ysdate <= DATE_FORMAT(NOW(),'%Y-%m-%d') \
		LIMIT "+str(30*int(numberpg))+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas

#搜索接口
@wenzhang.route('/search', methods=['POST','GET'])
def search_pg():
	if request.method == "GET":
		keys = request.args.get('keys')
	wz = search_wz(keys)
	print(wz)
	returnlist = wz_list_show(wz)
	#print(returnlist)
	return render_template('home.html', wzlist=returnlist, keyd=keys, htmltitle = "始终养生头条")
	#return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")



#分类搜索功能
@ManDB
def fenlei_wz(man_db,fl_keys,numberpg=0):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
		from szys_list where fenlei = '"+str(fl_keys)+"' \
		and ysdate <= DATE_FORMAT(NOW(),'%Y-%m-%d') \
		LIMIT "+str(30*int(numberpg))+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas

#分类搜索接口
@wenzhang.route('/fenleisearch', methods=['POST','GET'])
def fenlei_search_pg():
	if request.method == "GET":
		keys = request.args.get('keys')
	wz = fenlei_wz(keys)
	print(wz)
	returnlist = wz_list_show(wz)
	#print(returnlist)
	return render_template('home.html', wzlist=returnlist, keyd=keys, htmltitle = "始终养生头条")
	#return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")




#最火 - 今日
@ManDB
def hot_wz(man_db,numberpg=0):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
		from szys_list where ysdate = DATE_FORMAT(NOW(),'%Y-%m-%d') \
		ORDER BY ck_count DESC \
		LIMIT "+str(30*int(numberpg))+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas



#最新
@ManDB
def new_wz(man_db,numberpg=0):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
		from szys_list where ysdate = DATE_FORMAT(NOW(),'%Y-%m-%d') \
		ORDER BY ysdate DESC \
		LIMIT "+str(30*int(numberpg))+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas



#热评 - 今日
@ManDB
def pl_hot_wz(man_db,numberpg=0):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
		from szys_list where ysdate = DATE_FORMAT(NOW(),'%Y-%m-%d') \
		ORDER BY pl_count DESC \
		LIMIT "+str(30*int(numberpg))+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas



#首页文章 最火 - 今日  最新  热评 - 今日  选项
@wenzhang.route('/typewz', methods=['POST','GET'])
def type_wz_pg():
	if request.method == "GET":
		wztype = request.args.get('type')

	if wztype == "hot":
		wz = hot_wz()
		print(wz)
		returnlist = wz_list_show(wz)
		#return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")
		return render_template('home.html', wzlist=returnlist, hot=1, gettype="hot", htmltitle = "始终养生头条")
	elif wztype == "new":
		wz = new_wz()
		returnlist = wz_list_show(wz)
		#return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")
		return render_template('home.html', wzlist=returnlist, new=1, gettype="new", htmltitle = "始终养生头条")
	elif wztype == "plhot":
		wz = pl_hot_wz()
		returnlist = wz_list_show(wz)
		#return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")
		return render_template('home.html', wzlist=returnlist, plhot=1, gettype="plhot", htmltitle = "始终养生头条")
	




#下拉获取文章列表
@ManDB
def get_next_wz(man_db,numberpg):
	sql = "SELECT szys_id,title,imgpath,fenlei,ysdate,pl_count,ck_count,datatype \
			FROM `szys_list` \
			WHERE ysdate <= DATE_FORMAT(NOW(),'%Y-%m-%d') \
			order by ysdate DESC \
			LIMIT "+str(30*int(numberpg))+",30"
	return_datas = man_db.execute_seles(sql)
	return return_datas



#下拉
@wenzhang.route('/nextwz', methods=['POST','GET'])
def next_wz_pg():
	if request.method == "GET":
		get_type = request.args.get('gettype')
		number_pg = request.args.get('numb')
		keys = request.args.get('keys')
	print("next_wz_pg")
	print(get_type)
	print(number_pg)
	if get_type == "tj":
		wz = get_next_wz(number_pg)
	elif get_type == "hot":
		wz = hot_wz(number_pg)
	elif get_type == "new":
		wz = new_wz(number_pg)
	elif get_type == "plhot":
		wz = pl_hot_wz(number_pg)
	elif get_type == "search":
		wz = search_wz(keys,number_pg)
	elif get_type == "fenleisearch":
		wz = fenlei_wz(keys,number_pg)	

	returnlist = wz_list_show(wz)
	#print(returnlist)
	return json.dumps(returnlist).encode('utf-8').decode("unicode-escape")






